import axios from 'axios'
export default {
  namespaced: true,
  state: {
    list: [] //存储购物车数据
  },
  mutations: {
    // 更新list 数据
    updateList (state, newList) {
      state.list = newList
    },
    // 更新count
    updateCount (state, obj) {
      let row = state.list.find(item => item.id === obj.id)
      row.count = obj.count
    }
  },
  getters: {},
  actions: {
    // 发送 ajax 请求,获取购物车数据
    async getListAsync (store) {
      const { data: res } = await axios({
        method: 'GET',
        url: 'http://localhost:3000/list'
      })
      store.commit('updateList', res)
    },
    // 更新商品数量的方法
    async updateCountAsync (store, obj) {
      // 发送请求更新服务器数据
      await axios({
        method:'PATCH',
        url:`http://localhost:3000/list/${obj.id}`,
        data:obj
      })
      // 更新 vuex 中的数据
      store.commit('updateCount', obj)
    }
  }
}
